<template>
  <div id="project-edit" class="project-edit">
    <el-form ref="projectEditFormRef" :model="form" label-width="130px" :rules="rules">
      <el-form-item label="项目ID" style="display: none">
        <el-input v-model="form.projectId" />
      </el-form-item>
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model="form.projectName" />
      </el-form-item>
      <el-form-item label="项目编译根目录">
        <el-input v-model="form.projectRootDir" disabled />
      </el-form-item>
      <el-form-item label="主机IP" prop="sshHost">
        <el-input v-model="form.sshHost" />
      </el-form-item>
      <el-form-item label="端口号" prop="sshPort">
        <el-input v-model="form.sshPort" />
      </el-form-item>
      <el-form-item label="用户名" prop="sshUsername">
        <el-input v-model="form.sshUsername" />
      </el-form-item>
      <el-form-item label="密码" prop="sshPassword">
        <el-input v-model="form.sshPassword" show-password />
      </el-form-item>
      <el-form-item label="是否需要VPN">
        <el-radio-group v-model="form.isNeedVpn" v-removeAriaHidden @change="isNeedVpnSel">
          <el-radio label="1">是</el-radio>
          <el-radio label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="VPN配置文件路径" prop="vpnConfigPah">
        <el-input v-model="form.vpnConfigPah" :disabled="form.isNeedVpn === '0'" />
      </el-form-item>
      <el-form-item label="项目环境" prop="envHost">
        <div class="tags-wrapper">
          <el-tag v-for="(item, index) in form.envInfoList" :key="index" type="warning">{{ item.host }}</el-tag>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button @click="onCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getProjectEnvs, updateProjectInfo } from '@/api/project'

export default {
  name: 'ProjectEdit',
  emits: ['cancel-edit', 'submit-edit'],
  props: {
    projectInfo: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      form: {
        projectId: '',
        projectName: '',
        projectRootDir: '',
        sshHost: '',
        sshPort: 22,
        sshUsername: '',
        sshPassword: '',
        isNeedVpn: 0,
        vpnConfigPah: '',
        envInfoList: []
      },
      rules: {
        projectName: [{
          required: true, message: '项目名称不能为空', trigger: 'blur'
        }],
        sshHost: [{
          required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (!value) {
              return callback(new Error('主机IP不能为空'))
            }
            if (/^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$/.test(value)) {
              return callback()
            } else {
              return callback(new Error('请输入正确的IPv4地址'))
            }
          }
        }],
        sshPort: [{
          required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (!value) {
              return callback(new Error('端口号不能为空'))
            }
            if (/^([1-9](\d{0,3}))$|^([1-5]\d{4})$|^(6[0-4]\d{3})$|^(65[0-4]\d{2})$|^(655[0-2]\d)$|^(6553[0-5])$/.test(value)) {
              return callback()
            } else {
              return callback(new Error('端口号范围：1~65535'))
            }
          }
        }],
        sshUsername: [
          { required: true, message: '用户名不能为空', trigger: 'blur' },
          { min: 3, max: 32, message: '长度在 3 到 32 个字符', trigger: 'blur' }
        ],
        sshPassword: [{
          required: true, trigger: 'blur', message: '密码不能为空'
        }],
        vpnConfigPah: [
          {
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (this.form.isNeedVpn === '0') {
                return callback()
              }
              if (!value) {
                return callback(new Error('请输入VPN配置文件路径'))
              }
              if (value.length >= 1 && value.length <= 255) {
                return callback()
              } else {
                return callback(new Error('长度在 1 到 255 个字符'))
              }
            }
          }
        ]
      }
    }
  },
  async created() {
    // 初始化数据
    this.form = { ...this.projectInfo }
    // 获取环境信息
    const res = await getProjectEnvs({ projectId: this.$route.meta.projectId })
    const list = res.data
    if (list && list.length > 0) {
      this.$set(this.form, 'envInfoList', list)
    }
  },
  methods: {
    onSubmit() {
      // 提交后端并更新父组件数据
      this.$refs['projectEditFormRef'].validate((valid) => {
        if (valid) {
          const projectInfo = JSON.parse(JSON.stringify(this.form))
          delete projectInfo.envInfo
          updateProjectInfo(projectInfo).then(res => {
            this.$emit('submit-edit')
            this.$message.success('更新成功')
          }).catch(err => {
            console.error(err)
            this.$message.error('更新失败')
          })
        } else {
          return false
        }
      })
    },
    onCancel() {
      this.$emit('cancel-edit', false)
    },
    isNeedVpnSel() {
      if (this.form.isNeedVpn === '0') {
        this.$refs.projectEditFormRef.clearValidate('vpnConfigPah')
      }
    }
  }
}
</script>

<style>
.tags-wrapper {
  display: flex;
  flex-wrap: wrap;
  gap: 8px; /* 标签间距 */
  align-items: center;
  max-height: 100px; /* 最大高度限制 */
  overflow-y: auto; /* 超出滚动 */
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 5px;
}
</style>
